<template>
	<view class="tu-box bai left clearfix" style="height:100%;">
			<children-top title="文/图生视频" page="/pages/index/index"></children-top>
		
		<view class="top-content left clearfix">
			<view class="tu-left clearfix left">
				<view class="tim-left-title left clearfix">
					输入生成视频描述
					
					<label style="float:right;margin-right:20px;" title="作品列表" @click="navigatTo('/pages/works/works')">
						<uni-icons type="icon-component-full" size="25" color="#2979ff" custom-prefix="iconfont"></uni-icons>
					</label>
				</view>
				
				<create-textarea :fontTotalNumber="500" @change="getContent"></create-textarea>
			</view>
			
			<view class="tu-right right clearfix relative">
				<view class="tim-right-title left clearfix relative">
					视频生成
					<view class="tim-right-sucai right">
						<label>
							<uni-icons type="icon-wodezuopin" size="20" color="#666" custom-prefix="iconfont"></uni-icons>
						</label>
						<label>
							素材库
						</label>
						
					</view>
				</view>
				
				<view class="tim-type-box left clearfix relative">
					<view class="tim-type-item left" @click="videoType = 1" :style="videoType==1?'background:#fff;border-radius:7px;box-shadow: 0 0 4px 0 rgba(0, 0, 0, .15);color:#333;font-weight:500;':'background:none;border-radius:0;box-shadow: none;'">
						文生视频
					</view>
					
					<view class="tim-type-item left" @click="videoType = 2" :style="videoType==2?'background:#fff;border-radius:7px;box-shadow: 0 0 4px 0 rgba(0, 0, 0, .15);color:#333;font-weight:500;':'background:none;border-radius:0;box-shadow: none'">
						图生视频
					</view>
					
				</view>
				
				
				<!--图生视频模块-->
				<view class="tu-video-box left clearfix" v-if="videoType==2">
						
					<view class="tu-upload-box left clearfix">
						<view class="tim-right-title left">
							上传图片
							
							<view class="tim-right-sucai right">
								<label @click="imgNumber = 1" :style="imgNumber==1?'background:#2979ff;color:#fff;':'background:none;color:#333;'">单图</label>
								<label @click="imgNumber = 2" :style="imgNumber==2?'background:#2979ff;color:#fff':'background:none;color:#333;'">双图</label>
							</view>
							
						</view>
						
						<view class="tu-upload-image left clearfix" v-if="imgNumber==1">
							
							<view class="tu-upload-icon left clearfix" @click="chooseImage(1)"  v-if="!image || !image[1] || !image[1].url">
								<view class="tu-upload-icons left">
									<uni-icons type="plusempty" size="30" color="#ddd"></uni-icons>
								</view>
								<view class="tu-upload-text left">
									点击上传图片
								</view>
							</view>
							
							<view class="tu-upload-image-view left clearfix" v-if="image && image[1] && image[1].url">
								<view class="tu-images left clearfix relative" style="width:100%;height:100%;">
									<image v-if="image && image[1]" :src="image[1].url" style="width:100%;height:100%;" mode="aspectFill"></image>
									<view class="tu-image-close absolute" title="删除" @click="removeImage(1)">
										<uni-icons type="closeempty" size="20" color="#ddd"></uni-icons>
									</view>
								</view>
							</view>
							
							
							<zmt-circular-progress style="margin-top:calc((100% - 100px)/2)" :percent="percent" v-if="currentUploadItem == 1 && percent > 0 && percent < 100"></zmt-circular-progress>
							
						</view>
						
						
						<!--双图模式-->
						<view class="tu-upload-images left clearfix" v-if="imgNumber==2">
							
							<view class="tu-upload-items left clearfix"  @click="chooseImage(2)" v-if="!image || !image[2] ||  !image[2].url">
								<view class="tu-upload-icons left" style="margin-top:30px;">
									<uni-icons type="plusempty" size="30" color="#ddd"></uni-icons>
								</view>
								
								<view class="tu-upload-text left">
									上传首针图片
								</view>
								
								<zmt-circular-progress :width="70" :height="70" style="margin-top:calc((100% - 70px)/2)" :percent="percent" v-if="currentUploadItem == 2 && percent > 0 && percent < 100"></zmt-circular-progress>
							</view>
							
							<view class="tu-upload-items left clearfix" v-if="image && image[2] && image[2].url">
								<view class="tu-images left clearfix relative" style="width:100%;height:100%;">
									<image v-if="image && image[2]" :src="image[2].url" style="width:100%;height:100%;border-radius: 12px;" mode="aspectFill"></image>
									<view class="tu-image-close absolute" title="删除" @click="removeImage(2)">
										<uni-icons type="closeempty" size="20" color="#ddd"></uni-icons>
									</view>
								</view>
							</view>
							
							
							<view class="tu-upload-items left clearfix"  @click="chooseImage(3)"  v-if="!image || !image[3] || !image[3].url">
								<view class="tu-upload-icons left" style="margin-top:30px;">
									<uni-icons type="plusempty" size="30" color="#ddd"></uni-icons>
								</view>
								
								<view class="tu-upload-text left">
									上传尾帧图片
								</view>
								
								<zmt-circular-progress :width="70" :height="70" style="margin-top:calc((100% - 70px)/2)" :percent="percent" v-if="currentUploadItem == 3 && percent > 0 && percent < 100"></zmt-circular-progress>
								
							</view>
							
							
							<view class="tu-upload-items left clearfix" v-if="image && image[3] && image[3].url">
								<view class="tu-images left clearfix relative" style="width:100%;height:100%;">
									<image v-if="image && image[3]" :src="image[3].url" style="width:100%;height:100%;border-radius: 12px;" mode="aspectFill"></image>
									<view class="tu-image-close absolute" title="删除" @click="removeImage(3)">
										<uni-icons type="closeempty" size="20" color="#ddd"></uni-icons>
									</view>
								</view>
							</view>
							
							
							
						</view>
						
						
					</view>
				</view>
				<!--图生视频结束-->
				
				<!--文生视频开始-->
				<view class="wen-video-box left clearfix" v-if="videoType == 1">
					<!--尺寸列表-->
					<my-size title="视频比例" :data="sizeData" @selected="setSizeItem"></my-size>
				</view>
				<!--文生视频结束-->
				<my-size v-if="imgNumber!=2" title="视频品质" :data="model" @selected="setModel"></my-size>
				
				<!--智能扩写-->
				<view class="tu-kuoxie left clearfix">
					<label>智能扩写
					<uni-icons type="icon-bangzhu" @click="showTools = true" size="14" color="#666" custom-prefix="iconfont"></uni-icons>
					</label>
					<label>
						<switch :checked="promptExtend" @change="setPromptExtend" style="transform:scale(0.6)" />
					</label>
				</view>
				
				
				
				<view class="tim-submit left clearfix absolute" @click="createVideo()">
					生成视频
				</view>
				
			</view>
		</view>
		
		<up-modal :show="showTools" @confirm="showTools = false" content='开启后会对输入的内容进行智能改写。对于较短的内容生成效果提升明显，但会增加耗时。'></up-modal>
		<zmt-modal title="提交中" :show="modalShow" @close="modalShow = false" content="任务提交中···"></zmt-modal>
	</view>
</template>

<style scoped>
	.tu-upload-image-view image{border-radius: 12px;}
	.tu-image-close{width:30px;height:30px;border-radius: 50%;background:rgba(0,0,0,.7);line-height:30px;text-align: center;top:-5px;right:-5px;cursor:pointer;}
	.tu-upload-image-view{width:100%;height:100%;border-radius: 12px;}
	.tim-submit{width:80%;margin-left:10%;line-height:40px;background-image: linear-gradient(90deg, #4287fe, #298bfe 25%, #0f8ffd 51%, #25b4c1);color:#fff;text-align: center;border-radius: 10px;bottom:30px;left:0;right:0;cursor:pointer;}
	.tu-kuoxie label:last-child{float:right;margin-left:20px;line-height:30px;height:30px;margin-top:-2px;}
	.tu-kuoxie label:first-child{float:left;font-size:14px;color:#333;line-height:30px;}
	.tu-kuoxie{width:calc(100% - 40px);margin-left:25px;height:30px;margin-top:30px;}
	.wen-video-box{margin-top:30px;width:calc(100% - 20px);margin-left:10px;}
	.tu-upload-items{width:130px;height:130px;border-radius: 12px;background:#f7f8fc;margin-left:5px;margin-right:5px;}
	.tu-upload-images{width:100%;height:140px;margin-top:30px;}
	.tu-upload2-img{width:50%;height:100px;margin-top:calc((100% - 100px)/2 + 10px);}
	.tu-upload-img2-box{width:100%;height:100%;}
	.tu-upload-icons,.tu-upload-text{width:100%;line-height:30px;text-align: center;color:#999;font-size:13px;}
	.tu-upload-icon{width:200px;height:100px;margin-left:calc((100% - 200px)/2);margin-top:calc((100% - 100px)/2 + 10px);}
	.tu-upload-image{width:140px;height:140px;background:#f7f8fc;border-radius: 12px;margin-top:30px;margin-left:calc((100% - 140px)/2);}
	.tim-right-sucai label:first-child{border-right:1px solid #f8f8f8;}
	.tim-right-sucai label{font-size:12px;line-height:30px;float:left;width:49.5%;text-align: center;}
	.tu-upload-box{width:280px;margin-left:20px;margin-top:20px;height:250px;}
	.tim-type-item{width:calc(50% - 5px);height:35px;line-height:35px;margin:5px;margin-top:2.5px;margin-left:2.5px;margin-right:2.5px;cursor: pointer;position: relative;text-align: center;transition: color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);font-size:13px;color:#666;}
	.tim-type-box{width:calc(100% - 40px);margin-left:20px;background-color: rgba(0, 0, 0, 0.04);height:40px;margin-top:40px;border-radius: 7px;}
	.tim-right-sucai{margin-right:10px;height:30px;border:1px solid #eee;width:100px;border-radius: 15px;margin-top:-8px;overflow: hidden;}
	.tim-right-title{width:calc(100% - 20px);padding-left:20px;margin-top:20px;font-size:14px;color:#666;}
	.tim-left-title{width:calc(100% - 20px);padding-left:20px;lcolor: rgb(21, 27, 38);font-size: 18px;font-weight: 500;line-height: 28px;margin-top:20px;}
	.tim-left{width:70%;height:100%;background:#fff;border-radius: 15px;}
	.tu-left{width:calc(100% - 350px);height:100%;background:#fff;border-radius: 15px;}
	.top-content{width: 96%;height: calc(100% - 110px);margin-left: 2%;margin-top: 70px;}
	body, uni-page-body{height:100%;}
	.tu-right{width:320px;height:100%;background:#fff;border-radius: 15px;}
</style>

<script>
	var global =uniCloud.importObject('global',{customUI:true});
	var aliyun =uniCloud.importObject('aliyun',{customUI:true});
	var db = uniCloud.database();
	export default {
		data() {
			return {
				userinfo:{},//登录用户信息
				modalShow:false,
				content:'',//文本内容
				image:[],//上传之后的图片
				currentUploadItem:null,
				percent:0,
				promptExtend:true,//智能扩写
				showTools:false,
				videoType:1,//文生还是图生，1：文生，2：图生
				imgNumber:1,//单图还是双图，1：单图，2：双图
				size:'720*1280',
				proportion:'9:16',//比例
				modelItem:'wanx2.1-t2v-turbo',
				model:[
					{
						text:'标准',
						value:'wanx2.1-t2v-turbo'
					},
					{
						text:'高品质',
						value:'wanx2.1-t2v-plus'
					}
				],
				sizeData:[
					{
						text:'9:16',
						value:'720*1280',
						icon:'icon-rectangle1',
						size:15
					},
					{
						text:'16:9',
						value:'1280*720',
						icon:'icon-16gl-rectangle',
						size:15
					},
					{
						text:'1:1',
						value:'960*960',
						icon:'icon-checkbox',
						size:12
					},
					{
						text:'4:3',
						value:'1088*832',
						icon:'icon-16gl-rectangle',
						size:15
					},
					{
						text:'3:4',
						value:'832*1088',
						icon:'icon-rectangle1',
						size:15
					}
				],
			}
		},
		created() {
			var that = this;
			uni.getStorage({
				key:'login-userinfo',
				success:function(res){
					var userinfo = res.data;
					if(!userinfo || !userinfo._id){
						uni.navigateTo({
							url: '/pages/index/index'
						});
					}else{
						that.userinfo = userinfo;
					}
				},
				fail() {
					uni.navigateTo({
						url: '/pages/index/index'
					});
				}
			});
		},
		methods: {
			//创建视频
			createVideo(){
				var that = this;
				var videoType = that.videoType;
				if(videoType == 1){ //文生视频
					that.wenshengshipin();
				}else if(videoType == 2){
					that.tushengshipin();
				}
			},
			//图生视频
			tushengshipin(){
				if(this.imgNumber==1){
					this.tushengshipinOne();
				}else if(this.imgNumber == 2){
					this.tushengshipinTwo();
				}
			},
			
			//单图上传模式
			tushengshipinOne(){
				var model = this.modelItem;
				if(model =='wanx2.1-t2v-turbo'){
					model = 'wanx2.1-i2v-turbo';
				}else if(model =='wanx2.1-t2v-plus'){
					model = 'wanx2.1-i2v-plus';
				}
				var size = this.size;
				var content = this.content;
				var filePath = this.image[1].url;
				if(!filePath){
					uni.showToast({
						title:'请上传图片',
						icon:'none',
						position:'bottom'
					})
					return false;
				}
				if(!content){
					uni.showToast({
						title:'请输入您的指令内容',
						icon:'none',
						position:'bottom'
					})
					return false;
				}
				
				if(!model){
					uni.showToast({
						title:'请选择生成视频的品质',
						icon:'none',
						position:'bottom'
					})
					return false;
				}
				
				this.modalShow = true;
				var data = {
					model:model,
					input:{
						prompt:content,
						img_url:filePath
					},
					parameters:{
						duration:5
					}
				}
				
				var appId = '67cf931709664cc2d42ab0c9';
				aliyun.getVideoTaskId(data,appId).then(res=>{
					var userinfo = this.userinfo;
					var taskId = res.result.output.task_id;
					var taskStatus = res.result.output.task_status;
					var addData = {
						//应用信息
						app_title:'图生视频',
						app_id:appId,
						//用户信息
						uid:userinfo._id,
						content:content,
						task_id:taskId,
						size:this.size,
						type:'video',//类型
						task_status:taskStatus,
						task_status_text:'排队中'
					}
					db.collection('create_result').add(addData).then(addRes=>{
						this.modalShow = false;
						console.log('添加成功',addRes);
						//跳转到结果页面
						uni.redirectTo({
							url: '/pages/works/works'
						});
					}).catch(addErr=>{
						this.modalShow = false;
						console.log('添加失败',addErr);
					});
					
				}).catch(err=>{
					console.log('生成失败',err);
					
				});
			},
			//单图上传模式
			tushengshipinTwo(){
				var model = this.modelItem;
				if(model =='wanx2.1-t2v-turbo'){
					model = 'wanx2.1-i2v-turbo';
				}else if(model =='wanx2.1-t2v-plus'){
					model = 'wanx2.1-i2v-plus';
				}
				var size = this.size;
				var content = this.content;
				var firstFrameUrl = this.image[2].url;
				var lastFrameUrl  = this.image[3].url;
				if(!firstFrameUrl){
					uni.showToast({
						title:'请上传首针图片',
						icon:'none',
						position:'bottom'
					})
					return false;
				}
				if(!lastFrameUrl){
					uni.showToast({
						title:'请上传尾针图片',
						icon:'none',
						position:'bottom'
					})
					return false;
				}
				if(!content){
					uni.showToast({
						title:'请输入您的指令内容',
						icon:'none',
						position:'bottom'
					})
					return false;
				}
				
				if(!model){
					uni.showToast({
						title:'请选择生成视频的品质',
						icon:'none',
						position:'bottom'
					})
					return false;
				}
				
				this.modalShow = true;
				var data = {
					model:model,
					input:{
						prompt:content,
						first_frame_url:firstFrameUrl,
						last_frame_url:lastFrameUrl 
					},
					parameters:{
						duration:5
					}
				}
				
				var appId = '67cf931709664cc2d42ab0c9';
				aliyun.getVideoTaskId(data,appId).then(res=>{
					var userinfo = this.userinfo;
					var taskId = res.result.output.task_id;
					var taskStatus = res.result.output.task_status;
					var addData = {
						//应用信息
						app_title:'图生视频',
						app_id:appId,
						//用户信息
						uid:userinfo._id,
						content:content,
						task_id:taskId,
						size:this.size,
						type:'video',//类型
						task_status:taskStatus,
						task_status_text:'排队中'
					}
					console.log('添加数据',addData);
					db.collection('create_result').add(addData).then(addRes=>{
						this.modalShow = false;
						console.log('添加成功',addRes);
						//跳转到结果页面
						uni.redirectTo({
							url: '/pages/works/works'
						});
					}).catch(addErr=>{
						this.modalShow = false;
						console.log('添加失败',addErr);
					});
					
				}).catch(err=>{
					console.log('生成失败',err);
					
				});
			},
			//文生视频
			wenshengshipin(){
				var content = this.content;
				var size = this.size;
				var modelItem = this.modelItem;
				if(!content || content.length <5){
					uni.showToast({
						title:'请输入5个字以上的描述内容',
						icon:'none',
						duration:2000
					})
					
					return false;
				}
				
				if(!size){
					uni.showToast({
						title:'请选择视频比例',
						icon:'none',
						duration:2000
					})
					
					return false;
				}
				
				
				if(!modelItem){
					uni.showToast({
						title:'请选择视频品质',
						icon:'none',
						duration:2000
					})
					
					return false;
				}
				
				this.modalShow = true;
				
				var data = {
					model:modelItem,
					input:{
						prompt:content
					},
					parameters:{
						size:size,
						prompt_extend:this.promptExtend
					}
				}
				var appId = '67cf9c64a7c432861101ff7b';
				aliyun.getVideoTaskId(data,appId).then(res=>{
					var userinfo = this.userinfo;
					var taskId = res.result.output.task_id;
					var taskStatus = res.result.output.task_status;
					var time = new Date().getTime()
					var addData = {
						//应用信息
						app_title:'文生视频',
						app_id:appId,
						//用户信息
						uid:userinfo._id,
						content:content,
						task_id:taskId,
						size:size,//视频分辨率
						proportion:this.proportion,//视频比例
						type:'video',//类型
						task_status:taskStatus,
						task_status_text:'排队中'
					}
					
					db.collection('create_result').add(addData).then(addRes=>{
						this.modalShow = false;
						//跳转到结果页面
						uni.redirectTo({
							url: '/pages/works/works'
						});
					}).catch(addErr=>{
						this.modalShow = false;
					});
					
				});
				
				
			},
			//设置智能扩写
			setPromptExtend(e){
				this.promptExtend = e.detail.value;
			},
			//设置品质
			setModel(e){
				this.modelItem = e.value;
			},
			//获取编辑器内容
			getContent(e){
				this.content = e;
			},
			//选择尺寸以后
			setSizeItem(item){
				this.proportion = item.text;
				this.size = item.value;
			},
			//删除图片
			removeImage(item){
				var that = this;
				var image = that.image;
					uni.showLoading({
						title:'删除中'
					})
				
				if(image && image[item]){
					//删除图片
					var imgPath = image[item].url;
					global.removeFileByPath(imgPath).then(res => {
						uni.hideLoading()
						delete that.image[item];
						that.percent = 0;
							uni.showToast({
								title:'删除成功',
								icon:'none'
							})
						  
					  });
					  
					  
				}
				
			},
			//选择图片
			chooseImage(item){
				var that = this;
				that.currentUploadItem = item;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function (res) {
						var tempFilePaths = res.tempFilePaths[0];
						var size = res.tempFiles[0].size;
						var name = res.tempFiles[0].name;
						var fileName = that.generateUUIDWithExtension(name);//uuid文件名
						//获取图片信息
						uni.getImageInfo({
							src:tempFilePaths,
							success(image) {
								that.uploadImage(tempFilePaths,fileName,image,item);
							}
						});
					}
				});
			},
			//上传图片
			uploadImage(tempFilePaths,fileName,image,item){
				var that = this;
				uniCloud.uploadFile({
				        filePath: tempFilePaths,
				        cloudPath: fileName,
				        onUploadProgress: function(progressEvent) {
				          console.log(progressEvent);
				          var percentCompleted = Math.round(
				            (progressEvent.loaded * 100) / progressEvent.total
				          );
						  
						  that.percent = parseInt(percentCompleted);
				        },
				        success(res) {
							var filePath = res.fileID;
							image.url = filePath;
							that.image[item] = image;
							
							
						}
						
				      });
			},
			//uuid
			 generateUUIDWithExtension(fileName) {
			    // 从文件名中提取扩展名
			    const lastDotIndex = fileName.lastIndexOf('.');
			    let extension = '';
			    if (lastDotIndex!== -1) {
			        extension = fileName.slice(lastDotIndex);
			    }
			    // 生成 UUID
			    const uuid = crypto.randomUUID();
			    // 拼接 UUID 和扩展名
			    return uuid + extension;
			}
		}
	}
</script>

